<?php
namespace V1\Controller;

/**
 * 采集数据类
 *
 * 短信相关：发送
 *     
 * @author wangzhenxian
 * @package application.components 
 */
use V1\Model\TagModel;
use Think\Log;
class CollectController extends BaseController {
    

    /**
     * 实时股票行情数据入库
     */
    public function rtstocklistqq(){
        
        Log::record("开始采集股票数据",'INFO',true);
        
        $today=  date('Y-m-d');
    
        $isOpen = M('CommonCalendar')->where("exchangeCD='XSHG' AND calendarDate='{$today}'")->getField('isOpen');
       
        if(empty($isOpen)){//todo可以考虑发送一条短信或邮件给管理员。
           Log::record("当前日期不是交易日无需采集",'WARN',true);
           exit; 
        }
       $amBegintime= strtotime($today.' 07:00');
       $amEndtime= strtotime($today.' 11:35');
       $pmBegintime= strtotime($today.' 13:00');
       $pmEndtime= strtotime($today.' 15:10');
       $currentTime=time();
       
       if($currentTime< $amBegintime || $currentTime>$pmEndtime) exit; 
       if($currentTime>$amEndtime&&$currentTime<$pmBegintime) exit;
        
        $stockList = M('StockInfo')->where("state=1")->select(); 
        $dataList = array();
       
        
        foreach ($stockList as $key => $value) {
           
            $url = "http://qt.gtimg.cn/q={$value['stockcode']}";
            
            $result = \Org\Net\Http::fsockopenDownload($url);
            $result= mb_convert_encoding($result,"utf-8","gb2312");
            $params =  split('~', substr($result,  strpos($result, '=')+2));
           
            if(count($params)<>50) continue;
            $data=array();
            
            $data['stock_code'] = $value['stockcode'];
            $data['stock_name'] = $params[1];
            $data['open']=$params[5];
            $data['close']=$params[4];
            $data['current']=$params[3];
            $data['high']=$params[33];
            $data['low']=$params[34];
            $data['volume']=$params[36];
            $data['trunover']=$params[37];
            $data['chg']=  $params[31];
            $data['percent']=$params[32];
            $data['update_time'] =  NOW_TIME;
            
            $dataList[]= $data;
           
        }
        Log::record("采集股票数据结束，准备写入库中",'INFO',true);
        M('Stock'.  str_replace('-', '', $today),C('RealTimeStockDb')['DB_PREFIX'],C('RealTimeStockDb')['DB_CONN'])->addAll($dataList);
        Log::record("采集股票数据结束",'INFO',true);
    }
    
    public function kline() {
        //$symbol = 'SZ000001';
        
        $url='http://xueqiu.com/stock/forchartk/stocklist.json?symbol=SZ000002&period=1day&type=normal&begin=1400048230307&end=1431584230307&_=1431584230308';
        
        //$url ='http://xueqiu.com/stock/forchartk/stocklist.json?symbol=SZ000004&period=1month&type=normal&end=1431580799960&_=1431580799961';
        //$url ='http://xueqiu.com/stock/forchartk/stocklist.json?symbol=SZ000004&period=1week&type=normal&begin=1305436810774&end=1431580810774&_=1431580810775';
        
        $conf = array(
           'cookie'=>'Hm_lvt_1db88642e346389874251b5a1eded6e3=1430982675,1431053979,1431326975,1431580251; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1431655982; s=i9nyqrmm.1gclz06; xq_a_token=848a0f80fbe5339baf0628ceaf53f46aed8d2d20; xq_r_token=90ac60b5e5ccf7613616995eaf93e6832e4f302b; __utma=1.1340882889.1431595073.1431653352.1431655982.3; __utmc=1; __utmz=1.1431595073.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=1.1.10.1431655982; __utmt=1',
        );
        
       $out = \Org\Net\Http::fsockopenDownload($url,$conf);
       $result = json_decode($out,true);
       
       $model = M('Sz000002','','DB_HIS_SZ');

       foreach ($result['chartlist'] as $value) {
    
         $value['time'] = date('Y-m-d',  strtotime($value['time']));
         $value['ktype']=1;
           if($model->create($value)){
                  $model->add();
           } else {
                  echo $model->getError(); 
                  break;
           } 
         
       }
    }
    
    /**
     * 只有在交易日的早间才采集数据
     * 
     */
    public function index() {
       
       $statday=date('Y-m-d',NOW_TIME);
       $stathour=$statday.' 6'; 
       Log::record("开始采集{$stathour}的马蹄指数",'INFO',true);
       
       $isOpen = M('CommonCalendar')->where("exchangeCD='XSHG' AND calendarDate='{$statday}'")->getField('isOpen');
       if(empty($isOpen)){//todo可以考虑发送一条短信或邮件给管理员。
          Log::record("当前日期不是交易日无需采集",'WARN',true);
          exit; 
       }

       $where['A.stocktype'] = 'A';
       $where['A.stathour'] = $stathour.":00:00";
       
       $tagModel =  new TagModel();
       $list = $tagModel->queryList($where,'C1M desc');
    
       $newlist= $tagModel->getNewList($list,$stathour,'C desc');
      
       $dataList = array();
       foreach ($newlist as $key => $value) {
           $dataList[]=array('trading_day'=>$statday,'stock_order'=>$key+1,'stock_code'=>$value['stockcode'],
               'stock_name'=>$value['stockname'],'s_index'=>$value['S'],'stock_type'=>'A','create_time'=>NOW_TIME);
       }
       
       Log::record("采集马蹄指数数据结束，准备写入库中",'INFO',true);
       $result = M('MatiIndex')->addAll($dataList);
       if(empty($result)){//todo失败或成功可以考虑发送一条短信或邮件给管理员。
           Log::record("采集马蹄指数数据结束，写入库中失败",'ERR',true);
       }else{
           $this->mkgame($statday);
           Log::record("采集马蹄指数数据结束，写入库中成功",'INFO',true);
       }
    }
    /**
     * 生成今日热度前20的股票参与猜涨跌游戏。
     * 这个在mtindex程序执行完成后生成。
     */
    
    public function mkgame($day) {

        Log::record("开始生成{$day}热度前20的股票猜涨跌游戏",'INFO',true);
        
        $where=array(
            'trading_day'=>$day,
            'stock_order'=>array('elt',20),
            'stock_type'=>'A',
            'status'=>'0',
        );
        
        $result = M('MatiIndex')->where($where)->field('trading_day,stock_code')->order('stock_order desc')->select();
        
        $gameGulModel = D('GameDetail');
  
        foreach ($result as  $value) {
            $gameGulModel->mkGamesGul($value['trading_day'],$value['stock_code']);
        }
        //更新状态
        Log::record("结束生成{$day}热度前20的股票猜涨跌游戏",'INFO',true);
    }
    
    /**
     * 参与游戏股票实时行情数据入库 
    */
    public function joinGameStockRealtimeInfo(){
        
        Log::record("开始采集股票数据",'INFO',true);
        
        $today=  date('Y-m-d');
    
       $amBegintime= strtotime($today.' 07:00');
       $amEndtime= strtotime($today.' 11:35');
       $pmBegintime= strtotime($today.' 13:00');
       $pmEndtime= strtotime($today.' 15:10');
       $currentTime=time();
       
       if($currentTime< $amBegintime || $currentTime>$pmEndtime) exit; 
       if($currentTime>$amEndtime&&$currentTime<$pmBegintime) exit;
       
        $isOpen = M('CommonCalendar')->where("exchangeCD='XSHG' AND calendarDate='{$today}'")->getField('isOpen');
       
        if(empty($isOpen)){//todo可以考虑发送一条短信或邮件给管理员。
           Log::record("当前日期不是交易日无需采集",'WARN',true);
           exit; 
        }

        $where=array(
            'trading_day'=> $today,
            'stock_order'=>array('elt',20),
            'stock_type'=>'A',
            'status'=>'0',
        );
        
        $result = M('MatiIndex')->where($where)->field('stock_code')->order('stock_order desc')->cache("mtindex{$today}",3600)->select();
  
        $stockList = ['sz399006','sz399001','sh000001'];
        
        foreach ($result as $key => $value) {
            $stockList[] = getStockWithFlag($value['stock_code']);
        }   
        $dataList = array();
       
        foreach ($stockList as $value) {
           
            $url = "http://qt.gtimg.cn/q={$value}";
            
            $result = \Org\Net\Http::fsockopenDownload($url);
            $result= mb_convert_encoding($result,"utf-8","gb2312");
            $params =  split('~', substr($result,  strpos($result, '=')+2));
           
            if(count($params)<>50) continue;
            $data=array();
            
            $data['stock_code'] = $value;
            $data['stock_name'] = $params[1];
            $data['open']=$params[5];
            $data['close']=$params[4];
            $data['current']=$params[3];
            $data['high']=$params[33];
            $data['low']=$params[34];
            $data['volume']=$params[36];
            $data['trunover']=$params[37];
            $data['chg']=  $params[31];
            $data['percent']=$params[32];
            $data['update_time'] =  NOW_TIME;
            
            $dataList[]= $data;

        }
        Log::record("采集股票数据结束，准备写入库中",'INFO',true);
        M('Stock'.  str_replace('-', '', $today),C('RealTimeStockDb')['DB_PREFIX'],C('RealTimeStockDb')['DB_CONN'])->addAll($dataList);
        Log::record("采集股票数据结束",'INFO',true);
    }
}